<script lang="ts" setup>
import { queryFeeChangeLog, queryOrderChangeLog } from '@/api/record'
import {
  queryFeeChangeLogRequestData,
  queryFeeChangeLogTabelCol,
  queryOrderChangeLogRequestData,
  queryOrderChangeLogTableCol
} from '@/api/record/types/record'
import { useTable } from '@/hooks/useTable'
import { OperationType, ShortTermAdjustType } from '@/types/enum'
import { getToken } from '@/utils/cache/cookies'
import { FormInstance } from 'element-plus'
import { defineAsyncComponent, onMounted, reactive, ref, watchEffect } from 'vue'
import { useRoute } from 'vue-router'
import { copyEvent } from '@/utils'

import dayjs from 'dayjs'
defineOptions({
  name: 'AdjustRecordList'
})
const route = useRoute()
const activeName = ref<'fee' | 'term'>((route.query.activeName as 'fee' | 'term') ?? 'term')
const feeForm = reactive<queryFeeChangeLogRequestData>({
  orderId: route.query.orderId ? (route.query.orderId as string) : '',
  operationType: '',
  userId: route.query.userId ? (route.query.userId as string) : '',
  type: '',
  phone: ''
})
const termForm = reactive<queryOrderChangeLogRequestData>({
  orderId: route.query.orderId ? (route.query.orderId as string) : '',
  operationType: '',
  phone: ''
})
const operationType = ref<string>('')
const operationTypeOptions = [
  {
    label: '不限',
    value: ''
  },
  {
    label: '退费(骑行费)',
    value: '1+0'
  },
  {
    label: '退费(强制还车费)',
    value: '1+1'
  },
  {
    label: '退费(维修费)',
    value: '1+2'
  },
  {
    label: '退费(拖车费)',
    value: '1+3'
  },
  {
    label: '退费(违规费)',
    value: '1+4'
  },
  {
    label: '收费(骑行费)',
    value: '0+0'
  },
  {
    label: '收费(维修费)',
    value: '0+2'
  },
  {
    label: '收费(拖车费)',
    value: '0+3'
  },
  {
    label: '收费(违规费)',
    value: '0+4'
  }
]
watchEffect(() => {
  if (operationType.value === '') {
    feeForm.type = ''
    feeForm.operationType = ''
  } else {
    feeForm.type = +operationType.value.split('+')[0] as OperationType
    feeForm.operationType = +operationType.value.split('+')[1] as ShortTermAdjustType
  }
})
const feeFormRef = ref<FormInstance | null>(null)
const termFormRef = ref<FormInstance | null>(null)

const handleTermFormSearch = () => {
  setTermCurrentPage(1)
  termLoad()
}
const resetTermForm = () => {
  termFormRef.value?.resetFields()
}
const {
  pagination: termPagination,
  handleSizeChange: handleTermSizeChange,
  handleCurrentChange: handleTermCurrentChange,
  data: termData,
  loading: termLoading,
  setCurrentPage: setTermCurrentPage,
  load: termLoad
} = useTable<queryOrderChangeLogTableCol>(queryOrderChangeLog, getToken() ?? '', () => termForm)
const {
  pagination: feePagination,
  data: feeData,
  loading: feeLoading,
  handleSizeChange: handleFeeSizeChange,
  handleCurrentChange: handleFeeCurrentChange,
  setCurrentPage: setFeeCurrentPage,
  load: feeLoad
} = useTable<queryFeeChangeLogTabelCol>(queryFeeChangeLog, getToken() ?? '', () => feeForm)

const handleFeeFormSearch = () => {
  setFeeCurrentPage(1)
  feeLoad()
}
const resetFeeFrom = () => {
  feeFormRef.value?.resetFields()
  operationType.value = ''
}
const FeeBreakdownInfo = defineAsyncComponent(
  () => import('@/components/popover/FeeBreakdownInfo.vue')
)
const changePayStatusStyle = (payStatus: string) => {
  switch (payStatus) {
    case '已支付':
      return 'color:var(--xy-success-color)'
    case '待支付':
      return 'color:var(--xy-grey-text-color)'
    default:
      break
  }
}
const handleTabChange = () => {
  switch (activeName.value) {
    case 'fee':
      setFeeCurrentPage(1)
      feeLoad()
      break
    case 'term':
      setTermCurrentPage(1)
      termLoad()
      break
  }
}
onMounted(() => {
  handleTabChange()
})
</script>

<template>
  <div class="xy-container">
    <el-tabs v-model="activeName" @tab-change="handleTabChange">
      <el-tab-pane name="term" label="套餐调整记录">
        <el-form :model="termForm" inline ref="termFormRef">
          <el-form-item prop="phone" label="手机号">
            <el-input v-model="termForm.phone" />
          </el-form-item>
          <el-form-item prop="operationType" label="操作类型">
            <el-select v-model="termForm.operationType" style="width: 150px">
              <el-option label="不限" value="" />
              <el-option label="增加天/次数" value="0" />
              <el-option label="减少逾期天数" value="2" />
              <el-option label="扣除天数/次数" value="1" />
            </el-select>
          </el-form-item>
          <el-form-item prop="orderId" label="订单号">
            <el-input v-model="termForm.orderId" />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleTermFormSearch">查询</el-button>
            <el-button plain @click="resetTermForm">重置</el-button>
          </el-form-item>
        </el-form>
        <el-table :data="termData" v-loading="termLoading" class="no-border">
          <el-table-column
            prop="mobilePhone"
            label="手机号"
            align="center"
            min-width="150"
            fixed="left"
          />
          <el-table-column prop="orderType" label="套餐类型" min-width="120" align="center" />
          <el-table-column prop="orderId" label="订单" min-width="300" align="center">
            <template #default="scope">
              <div class="flex-align-center">
                <span>{{ scope.row.orderId }}</span
                >&nbsp;
                <span @click="copyEvent(scope.row.orderId)" class="is-reference">复制</span>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="operationType" label="操作类型" min-width="120" align="center" />
          <el-table-column prop="duration" label="时长/次数" min-width="150" align="center" />
          <el-table-column
            prop="reason"
            label="调整原因"
            align="center"
            min-width="150"
            show-overflow-tooltip
          />
          <el-table-column
            prop="createdTime"
            label="调整时间"
            sortable
            min-width="200"
            align="center"
          >
            <template #default="scope">
              <span>{{ dayjs(scope.row.createdTime).format('YYYY-MM-DD HH:mm:ss') }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="operator" label="操作人" align="center" show-overflow-tooltip />
        </el-table>
        <div flex justify-end mt-20>
          <el-pagination
            @current-change="handleTermCurrentChange"
            @size-change="handleTermSizeChange"
            v-model:current-page="termPagination.pageNum"
            v-model:page-size="termPagination.pageSize"
            background
            :total="termPagination.total"
            layout="total,prev,pager,next,jumper,sizes"
          />
        </div>
      </el-tab-pane>
      <el-tab-pane name="fee" label="费用调整记录">
        <el-form :model="feeForm" ref="feeFormRef" inline>
          <el-form-item prop="phone" label="手机号">
            <el-input v-model="feeForm.phone" placeholder="请输入手机号" />
          </el-form-item>
          <el-form-item label="调整类型">
            <el-select v-model="operationType" placeholder="请选择调整类型" style="width: 140px">
              <el-option
                v-for="(type, index) in operationTypeOptions"
                :key="index"
                :label="type.label"
                :value="type.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item prop="orderId" label="行程编号">
            <el-input v-model="feeForm.orderId" placeholder="请输入行程编号" />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleFeeFormSearch">查询</el-button>
            <el-button plain @click="resetFeeFrom">重置</el-button>
          </el-form-item>
        </el-form>
        <el-table :data="feeData" v-loading="feeLoading">
          <el-table-column
            prop="phone"
            label="用户手机号"
            align="center"
            min-width="150"
            fixed="left"
          />
          <el-table-column
            prop="orderId"
            label="行程编号"
            align="center"
            min-width="250"
            show-overflow-tooltip
          />
          <el-table-column prop="totalAmount" label="总费用" align="center">
            <template #default="scope">
              <el-popover
                placement="bottom"
                title="费用明细"
                width="auto"
                trigger="hover"
                v-if="
                  JSON.stringify(scope.row.tradeExtensionData) !== '{}' &&
                  scope.row.tradeExtensionData
                "
              >
                <template #reference>
                  <span class="cursor-pointer" style="color: var(--xy-grey-text-color)">{{
                    scope.row.totalAmount
                  }}</span>
                </template>
                <template #default>
                  <fee-breakdown-info :data="scope.row.tradeExtensionData" />
                </template>
              </el-popover>
              <span style="color: var(--xy-grey-text-color)" v-else>{{
                scope.row.rideAmount
              }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="deductionType" label="抵扣方式" align="center" />
          <el-table-column prop="payStatus" label="支付状态" align="center" min-width="120">
            <template #default="scope">
              <el-popover
                placement="bottom"
                title="待付费用明细"
                width="auto"
                trigger="click"
                v-if="
                  JSON.stringify(scope.row.waitPayExtensionData) !== '{}' &&
                  scope.row.waitPayExtensionData
                "
              >
                <template #reference>
                  <span class="cursor-pointer" :style="changePayStatusStyle(scope.row.payStatus)">{{
                    scope.row.payStatus
                  }}</span>
                </template>
                <template #default>
                  <fee-breakdown-info :data="scope.row.waitPayExtensionData" />
                </template>
              </el-popover>
              <span v-else :style="changePayStatusStyle(scope.row.payStatus)">{{
                scope.row.payStatus
              }}</span>
            </template>
          </el-table-column>
          <el-table-column
            prop="operationType"
            label="调整类型"
            align="center"
            min-width="150"
            show-overflow-tooltip
          />
          <el-table-column prop="amount" label="金额" align="center" />
          <el-table-column prop="discountCoupon" label="优惠金额" align="center" />
          <el-table-column prop="reason" label="原因" align="center" show-overflow-tooltip />
          <el-table-column
            prop="changeTime"
            label="操作时间"
            min-width="250"
            show-overflow-tooltip
            align="center"
          />
          <el-table-column
            prop="operator"
            label="操作人"
            width="150"
            show-overflow-tooltip
            align="center"
          />
        </el-table>
        <div flex justify-end mt-20>
          <el-pagination
            @current-change="handleFeeCurrentChange"
            @size-change="handleFeeSizeChange"
            v-model:current-page="feePagination.pageNum"
            v-model:page-size="feePagination.pageSize"
            background
            :total="feePagination.total"
            layout="total,prev,pager,next,jumper,sizes"
          />
        </div>
      </el-tab-pane>
    </el-tabs>
  </div>
</template>

<style scoped></style>
